/**
 * Created by 叶子 on 2017/7/30.
 * http通用工具函数
 */
import axios from 'axios';
import {message} from 'antd';
import umbrella from 'umbrella-storage';
import { time } from 'console';

//const baseUrl = process.env.NODE_ENV === 'development' ? '' : 'http://47.100.31.123:8080/';
// const baseUrl =  'http://47.100.31.123:8080/';
const remoteUrl = 'http://47.104.241.253:8080';
let baseUrl = process.env.NODE_ENV === 'development' ? '/op' : process.env.NODE_ENV === 'production' ? remoteUrl : '/op';
console.log('baseUrl', baseUrl);
console.log('process.env.NODE_ENV', process.env.NODE_ENV);

interface IFRequestParam {
    url: string;
    msg?: string;
    config?: any;
    data?: any;
}

/**
 * 服务器返回体
 */
export interface Resp<T> {
    resultCode: string;
    statusCode: string;
    msg: string;
    result: T;
    data:T;
}

export const getUrl=()=>{
  const ip :string = umbrella.getLocalStorage("ip");
  return (ip && ip.length>0) ? ip : baseUrl;
}

export const baseGet = ({ url, msg = '接口异常', config }: IFRequestParam) =>{

  return axios
    .get(url, config)
    .then((res) => res.data)
    .catch((err) => {
        console.log(err);
        messageBox(msg);
    });
}

/**
 * 公用get请求
 * @param url       接口地址
 * @param msg       接口异常提示
 * @param headers   接口所需header配置
 */
export const get = ({ url, msg = '接口异常', config }: IFRequestParam) =>{
  const _url = umbrella.getLocalStorage("ip") ? umbrella.getLocalStorage("ip") : baseUrl;
  return axios
    .get(_url + url, config)
    .then((res) => res.data)
    .catch((err) => {
        console.log(err);
        messageBox(msg);
    });
}


export const download=(downloadUrl:string)=>{
  const _url = umbrella.getLocalStorage("ip") ? umbrella.getLocalStorage("ip") : baseUrl;
  const user = umbrella.getLocalStorage('user');
  let headers = null;
  if (user && user.token) {
      headers = { 
        'X-EI-Token': user.token,
        "Access-Control-Allow-Origin":"*" ,
        "Content-Type":"application/x-www-form-urlencoded",
        mode: 'no-cors',
      };
  } else {
      headers = { };
  }


    axios({
      method: 'get',
      url: _url+downloadUrl,
      responseType: 'blob',
      headers
    }).then( res => {
      if(!res) {
        return
      }
      console.log("response: ", res);
        // new Blob([data])用来创建URL的file对象或者blob对象
        let url = window.URL.createObjectURL(new Blob([res.data]));
        // 生成一个a标签
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        // 生成时间戳
        //TODO 通过请求头拿到文件名
        let timestamp=new Date().getTime();
        link.download = timestamp + ".xlsx";
        document.body.appendChild(link);
        link.click();
    })
}


/**
 * 公用post请求
 * @param url       接口地址
 * @param data      接口参数
 * @param msg       接口异常提示
 * @param headers   接口所需header配置
 */
export const post = ({ url, data, msg = '接口异常' }: IFRequestParam) => {
    const _url = umbrella.getLocalStorage("ip") ? umbrella.getLocalStorage("ip") : baseUrl;
    const user = umbrella.getLocalStorage('user');
    let headers = null;
    if (user && user.token) {
      headers = { };
  } else {
      headers = { };
  }
    console.log("请求路径：", baseUrl + url)
    return axios
        .post(_url + url, data, { headers })
        .then((res) => {
            let resp = res.data as Resp<any>;
            // if(!resp.statusCode){
            //   const json = Base64.decode(res.data);
            //   resp = JSON.parse(json) as Resp<any>;
            //   console.log("atob:",res.data,json);
            // }
            if (resp.statusCode !== '200') {
                messageBox(resp.msg);
                // window.history.go
            }
            return resp;
        })
        .catch((err) => {
            console.log(err);
            messageBox(msg);
            const errResp: Resp<string> = {
                resultCode: '500',
                statusCode: '500',
                msg: msg,
                result: '',
                data:'',
            };
            return errResp;
        });
};

/**
 * 代理接口
 * url加上了api，会被代理掉
 * @param param
 */
export const zbPost = ({ url, data, msg = '接口异常' }: IFRequestParam) => {
    const _url = umbrella.getLocalStorage("ip") ? umbrella.getLocalStorage("ip") : baseUrl;
    const user = umbrella.getLocalStorage('user');
    let headers = null;
    if (user && user.token) {
        headers = { };
    } else {
        headers = { };
    }
    // const url =
    console.log("请求路径：", baseUrl + url);
//     let url =
    return axios
        .post(_url + url, data, { headers })
        .then((res) => {
            // debugger;
            let resp = res.data as Resp<any>;
            // if(!resp.statusCode){
            //   const json = Base64.decode(res.data);
            //   // const json = Base64.stringify(res.data);
            //   console.log("atob:",res.data,json);
            //   resp = JSON.parse(json) as Resp<any>;
            // }
            if (resp.statusCode !== '200') {
                messageBox(resp.msg);
                // window.history.go
            }
            return resp;
        })
        .catch((err) => {
            console.log(err);
            messageBox(msg);
            const errResp: Resp<string> = {
                resultCode: '500',
                statusCode: '500',
                msg: msg,
                result: '',
                data:'',
            };
            return errResp;
        });
};

const messageBox=(msg : string)=>{
    msg && message.warn(msg);
}

export const zbGet = ({ url, msg = '接口异常', config }: IFRequestParam) => {
    const _url = umbrella.getLocalStorage("ip") ? umbrella.getLocalStorage("ip") : baseUrl;
    const user = umbrella.getLocalStorage('user');
    let headers = null;
    if (user && user.token) {
      headers = { };
  } else {
      headers = { };
  }
    console.log("请求路径：", baseUrl + '/op' + url)
    return axios
        .get(_url + url, { headers })
        .then((res) => {
            let resp = res.data as Resp<any>;
            if(!resp.statusCode){
              const json = Base64.decode(res.data);
              console.log("atob:",res.data,json);
              resp = JSON.parse(json) as Resp<any>;
            }
            if (resp.statusCode !== '200') {
                messageBox(resp.msg);
                // window.history.go
            }
            return resp;
        })
        .catch((err) => {
            console.log(err);
            messageBox(msg);
            const errResp: Resp<string> = {
                resultCode: '500',
                statusCode: '500',
                msg: msg,
                result: '',
                data:'',
            };
            return errResp;
        });
};


let Base64 = {
  // encode(str:string) {
  //     // first we use encodeURIComponent to get percent-encoded UTF-8,
  //     // then we convert the percent encodings into raw bytes which
  //     // can be fed into btoa.
  //     return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  //         function toSolidBytes(match, p1) {
  //             return String.fromCharCode("0x" + p1);
  //         }));
  // },
  decode(str:string) {
      // Going backwards: from bytestream, to percent-encoding, to original string.
      return decodeURIComponent(atob(str).split('').map(function (c) {
          return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
      }).join(''));
  }
};
